package com.example.system.service.exam.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.core.constants.Constants;
import com.example.common.core.domin.R;
import com.example.common.core.domin.TableDataInfo;
import com.example.common.core.enums.ResultCode;
import com.example.common.redis.service.RedisService;
import com.example.common.security.exception.ServiceException;
import com.example.system.domin.exam.Exam;
import com.example.system.domin.exam.ExamQuestion;
import com.example.system.domin.exam.dto.ExamAddDTO;
import com.example.system.domin.exam.dto.ExamEditDTO;
import com.example.system.domin.exam.dto.ExamQueryDTO;
import com.example.system.domin.exam.dto.ExamQuestAddDTO;
import com.example.system.domin.exam.vo.ExamDetailVO;
import com.example.system.domin.exam.vo.ExamVO;
import com.example.system.domin.question.Question;
import com.example.system.domin.question.vo.QuestionVO;
import com.example.system.manager.ExamCacheManager;
import com.example.system.mapper.exam.ExamMapper;
import com.example.system.mapper.exam.ExamQuestionMapper;
import com.example.system.mapper.question.QuestionMapper;
import com.example.system.service.exam.IExamService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class ExamServiceImpl extends ServiceImpl<ExamQuestionMapper,ExamQuestion> implements IExamService {
    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private ExamQuestionMapper examQuestionMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Override
    public List<ExamVO> list(ExamQueryDTO examQueryDTO) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        return examMapper.selectExamList(examQueryDTO);
    }

    @Override
    public String add(ExamAddDTO examAddDTO) {
        checkExamSaveParams(examAddDTO,null);
        Exam exam = new Exam();
        BeanUtils.copyProperties(examAddDTO, exam);
        examMapper.insert(exam);
        return exam.getExamId().toString();//这块返回添加竞赛的id,前端要用这个id进行判断
    }

    @Override
    public boolean questionAdd(ExamQuestAddDTO examQuestAddDTO) {
        //先判断竞赛是否存在
        Exam exam = getExam(examQuestAddDTO.getExamId());
        //判断当前竞赛是否能进行操作(是否开赛)
        checkExam(exam);
        if (Constants.TRUE.equals(exam.getStatus())) {
            throw new ServiceException(ResultCode.EXAM_IS_PUBLISH);
        }
        Set<Long> questionIdSet = examQuestAddDTO.getQuestionIdSet();
        if(CollectionUtil.isEmpty(questionIdSet)){
            return true;
        }
        //批量查询数据 --- selectBatchIds
        List<Question> questionList = questionMapper.selectBatchIds(questionIdSet);
        if(CollectionUtil.isEmpty(questionList) || questionList.size() < questionIdSet.size()){
            throw new ServiceException(ResultCode.EXAM_QUESTION_NOT_EXISTS);
        }
        return saveExamQuestion(exam,questionIdSet);
    }

    @Override
    public ExamDetailVO detail(long examId) {
        ExamDetailVO examDetailVO = new ExamDetailVO();
        Exam exam = getExam(examId);

        BeanUtils.copyProperties(exam, examDetailVO);
        List<ExamQuestion> examQuestionList = examQuestionMapper.selectList(new LambdaQueryWrapper<ExamQuestion>()
                .select(ExamQuestion::getQuestionId)
                .eq(ExamQuestion::getExamId, examId)
                .orderByAsc(ExamQuestion::getQuestionOrder));
        if(CollectionUtil.isEmpty(examQuestionList)){
            //如果没有题目数据就直接返回即可
            return examDetailVO;
        }
        //获取题目id集合
        List<Long> questionIdList = examQuestionList.stream().map(ExamQuestion::getQuestionId).toList();
        //将所有相关的题目查询出来
        //select * from tb_question in (xx,xx,xx)
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId,Question::getTitle,Question::getDifficulty)
                .in(Question::getQuestionId, questionIdList));
//        List<QuestionVO> questionVOList = new ArrayList<>();
        //数据转换
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionList, QuestionVO.class);

        examDetailVO.setExamQuestionList(questionVOList);
        return examDetailVO;
    }

    //编辑题目基本信息
    @Override
    public int edit(ExamEditDTO examEditDTO) {
        //先找到要编辑的竞赛
        Exam exam = getExam(examEditDTO.getExamId());
        if(Constants.TRUE.equals(exam.getStatus())) {
            throw new ServiceException(ResultCode.EXAM_IS_PUBLISH);
        }
        //判断当前竞赛是否能进行操作(是否开赛)
        checkExam(exam);
        //校验参数
        checkExamSaveParams(examEditDTO, examEditDTO.getExamId());
        exam.setTitle(examEditDTO.getTitle());
        exam.setStartTime(examEditDTO.getStartTime());
        exam.setEndTime(examEditDTO.getEndTime());

        return examMapper.updateById(exam);
    }

    //删除竞赛中的题目
    @Override
    public int questionDelet(Long examId, Long questionId) {
        Exam exam = getExam(examId);
        //判断当前竞赛是否能进行操作(是否开赛)
        checkExam(exam);
        if (Constants.TRUE.equals(exam.getStatus())) {
            throw new ServiceException(ResultCode.EXAM_IS_PUBLISH);
        }
        return examQuestionMapper.delete(new LambdaQueryWrapper<ExamQuestion>()
                .eq(ExamQuestion::getExamId, examId)
                .eq(ExamQuestion::getQuestionId, questionId));
    }

    //删除竞赛
    @Override
    public int delete(Long examId) {
        Exam exam = getExam(examId);
        checkExam(exam);
        if(Constants.TRUE.equals(exam.getStatus())) {
            throw new ServiceException(ResultCode.EXAM_IS_PUBLISH);
        }
        //这块没必要去判断该竞赛是否有题目信息,直接删一下试试即可(试错成本不高)
        examQuestionMapper.delete(new LambdaQueryWrapper<ExamQuestion>()
                .eq(ExamQuestion::getExamId, examId));
        return examMapper.deleteById(examId);
    }

    //发布竞赛
    @Override
    public int publish(Long examId) {
        Exam exam = getExam(examId);
        //不能发布已完赛的竞赛
        if(exam.getEndTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_IS_FINISH);
        }
        //验证竞赛中是否存在题目
        Long count = examQuestionMapper.selectCount(new LambdaQueryWrapper<ExamQuestion>()
                .eq(ExamQuestion::getExamId, examId));
        if(count == null || count <= 0){
            throw new ServiceException(ResultCode.EXAM_NOT_HAS_QUESTION);
        }
        exam.setStatus(Constants.TRUE);
        //要将新发布的竞赛数据存储到redis e:t:l  e:d:examId
        examCacheManager.addCache(exam);

        return examMapper.updateById(exam);
    }

    @Override
    public int cancelPublish(Long examId) {
        Exam exam = getExam(examId);
        checkExam(exam);
        //已经结束的竞赛不能撤销发布
        if(exam.getEndTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_IS_FINISH);
        }
        exam.setStatus(Constants.FALSE);
        examCacheManager.deleteCache(exam.getExamId());
        return examMapper.updateById(exam);
    }

    private void checkExamSaveParams(ExamAddDTO examSaveDTO,Long examId) {
        //1.竞赛标题的重复性判断 2,竞赛开始时间和结束时间的判断
        List<Exam> exams = examMapper
                .selectList(new LambdaQueryWrapper<Exam>()
                        .eq(Exam::getTitle, examSaveDTO.getTitle())
                        .ne(examId != null,Exam::getExamId, examId));//examId != null的时候才会进行判断
        if(CollectionUtil.isNotEmpty(exams) ){
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }
        //添加对时间的判断
        if (examSaveDTO.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.EXAM_START_TIME_BEFORE_CURRENT_TIME);
        }
        if (examSaveDTO.getStartTime().isAfter(examSaveDTO.getEndTime())) {
            throw new ServiceException(ResultCode.EXAM_START_TIME_AFTER_END_TIME);
        }
    }

    private void checkExam(Exam exam) {
        //判断当前竞赛是否能进行操作(是否开赛)
        if (exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
    }

    //批量插入exam_question数据
    private boolean saveExamQuestion(Exam exam, Set<Long> questionIdSet) {
        int num = 1;
        List<ExamQuestion> examQuestionList = new ArrayList<>();
        for (Long questionId : questionIdSet) {
            ExamQuestion examQuestion = new ExamQuestion();
            examQuestion.setExamId(exam.getExamId());
            examQuestion.setQuestionId(questionId);
            examQuestion.setQuestionOrder(num++);
            examQuestionList.add(examQuestion);
        }
        return saveBatch(examQuestionList);
    }

    private Exam getExam(Long examId) {
        Exam exam = examMapper.selectById(examId);
        if (exam == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        return exam;
    }
}
